import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { Toast } from 'vant';
import { getCookie } from "@/util/cookie";
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "User" */ '../views/User.vue'),
  },
  {
    path: '/topic',
    name: 'Topic',
    component: () => import(/* webpackChunkName: "topic" */ '../views/Topic.vue'),
  },
  {
    path: '/catalog',
    name: 'Catalog',
    component: () => import(/* webpackChunkName: "catalog" */ '../views/Catalog.vue'),
  },
  {
    path: '/channel/:id',
    name: 'Channel',
    component: () => import(/* webpackChunkName: "channel" */ '../views/Channel.vue'),
  },
  {
    path: '/shopcar',
    name: 'ShopCar',
    component: () => import(/* webpackChunkName: "shopcar" */ '../views/ShopCar.vue'),
  },
  {
    path: '/details/:id',
    name: 'Details',
    component: () => import(/* webpackChunkName: "details" */ '../views/Details.vue'),
  },
  {
    path: '/branddetail/:id',
    name: 'Branddetail',
    component: () => import(/* webpackChunkName: "branddetail" */ '../views/Branddetail.vue'),
  },
  {
    path: '/user/address',
    name: 'Address',
    component: () => import(/* webpackChunkName: "address" */ '../views/Address.vue'),
  },
  {
    path: '/user/editaddress/:id',
    name: 'EditAddress',
    component: () => import(/* webpackChunkName: "editaddress" */ '../views/EditAddress.vue'),
  },
  {
    path: '/user/coupon',
    name: 'Coupon',
    component: () => import(/* webpackChunkName: "coupon" */ '../views/MyCoupon.vue'),
  },
  {
    path: '/user/feedback',
    name: 'Feedback',
    component: () => import(/* webpackChunkName: "feedback" */ '../views/Feedback.vue'),
  },
]
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 验证
const Safe = (next) => {
  let token = getCookie('token')
  if (token != null) {
    next()
  } else {
    Toast.fail('请登录')
  }
}

router.beforeEach((to, from, next) => {
  if (to.name != from.name) {
    store.commit('changeupPage', from.path)
  }

  switch (to.path) {
    case "/shopcar":
      Safe(next)
      break;
    case "/user/address":
      Safe(next)
      break;
    default:
      next()
      break;
  }
})
export default router
